import urllib2, urllib
from hashlib import md5
import base64
import os

"""
Send the data to the server and returns status

Params:
    serverurl - url to server script
    data -  dictionary containing key/value pairs
            This dictionary must contain "clientname" key
    imgfilename - filename of screenshot image
    md5phrase - simple hashing protection in order to avoid uploading data
                from 3rd party clients
Returns:
    dictionary containing two keys:
        ok - True/False
        error - None if there are no errors or
                error description in case of errors
"""
def send_data(serverurl,data,imgfilename=None,md5Phrase='12345'):
    ret={'ok':False,'error':'Undefined'}
    if data.has_key('clientname')==False:
        ret['error']="clientname is not set"
    else:
        #lets read the imgfile
        ok=True
        if imgfilename:
            f=None
            try:
                f=open(imgfilename,'rb')
            except:
                pass
            if f:
                tmp=f.read()
                f.close()
                #encode the filedata to base64
                tmp=base64.b64encode(tmp)
                fileName, fileExtension = os.path.splitext(imgfilename)
                #pass the filedata
                data['_filedata']=tmp
                #pass the file extension so server can use it when saving file
                data['_fileext']=fileExtension
            else:
                ok=False
                ret['error']="Failed to open input file ( %s )"%imgfilename
        if ok:
            mydata=[]
            md5base=md5Phrase
            for k in sorted(data.keys()):
                mydata.append((k,data[k]))
                md5base=md5base + k + str(data[k])
            mydata.append(('_md5',md5(md5base).hexdigest()))
            mydata=urllib.urlencode(mydata)
            req=urllib2.Request(serverurl, mydata)
            req.add_header("Content-type", "application/x-www-form-urlencoded")
            try:
                page=urllib2.urlopen(req).read()
                if page=="OK":
                    ret['ok']=True
                    ret['error']=None
                else:
                    ret['error']="Server message - "+page
            except urllib2.URLError as e:
                ret['error']=e.reason

    return ret
